﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NetMQ;

namespace NETMQLib
{
    public class RepMQ
    {
        NetMQ.Sockets.ResponseSocket socket = null;
        public event Func<string,string> ReceiveFrameStringEvent;
        public BaseMQModel BaseMQInfo { get; set; }

        string url = "";
        public RepMQ(string ip, int port)
        {
            try
            {
                BaseMQInfo = new BaseMQModel() { IP = ip, Port = port };
                url = $"inproc://{ip}:{port}";
                socket = new NetMQ.Sockets.ResponseSocket();
                socket.Bind(url);
                Thread recvThread = new Thread(new ThreadStart(RecvStringHand));
                recvThread.IsBackground = true;
                recvThread.Priority = ThreadPriority.AboveNormal;
                recvThread.Start();
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
        }

        void RecvStringHand()
        {
            while (true)
            {
                try
                {
                    string msg = socket.ReceiveFrameString(out bool hasMore);
                    if (msg == "exit")
                    {
                        break;
                    }
                    string backMsg = ReceiveFrameStringEvent?.Invoke(msg);
                    socket.SendFrame(backMsg, hasMore);
                }
                catch
                {
                    if (socket.IsDisposed)
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                    continue;
                }
            }
        }

        public void Dispose()
        {
            if (socket != null && !socket.IsDisposed)
            {
                socket.Unbind(url);
                socket.Close();
                socket.Dispose();
            }
        }
    }
}
